const Koa = require('koa');
// 路由配置
const route = require('koa-route');
const fs = require('fs')
// 允许静态资源被访问 直接在路径后面跟着资源名字即可
const static = require('koa-static')
const staticPath = './asset'
const path = require('path')
// const koaBody = require('koa-body');
const cors = require('koa2-cors');
var urlencode = require('urlencode');

const bodyParser = require("koa-bodyparser")
const compress = require('koa-compress');
const options = { 
  threshold: 10240 //数据超过1kb时压缩
};
const app = new Koa();

// 重定向
const redirect = ctx => {
  ctx.response.redirect('/');
};

const main = ctx => {
  ctx.response.body = '呵呵'
};

const saveJson = async ctx => {
  let body = ctx.request.body
  await fs.writeFile(`./asset/img/${urlencode.decode(body.fileName,'utf8')}.json`,JSON.stringify({storageArr:body.storageArr,textArr:body.textArr}), error => {
    if (error) {
      ctx.response.body = '保存失败'
    }else {
      ctx.response.body = '保存成功'
      ctx.body = 200; 
    }
  });
}

// 使用中间件
app.use(async (ctx, next)=> {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (ctx.method == 'OPTIONS') {
    ctx.body = 200; 
  } else {
    await next();
  }
});
app.use(compress(options));
app.use(bodyParser({
  formLimit: '3mb'
}))
app.use(static(
  path.join(__dirname, staticPath)
))
app.use(route.get('/', main));
app.use(route.get('/temp', redirect));
app.use(route.post('/saveJson', saveJson));


app.listen(2335, () => {
  console.log('server start')
});